package kayao.monitor;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.*;
import java.util.Vector;

import javax.swing.*;

import kayao.common.Client;
import kayao.common.KayaoValues;
import kayao.server.AreaManager;

public class ServerMonitor extends JFrame implements KeyListener, ActionListener
{
	private static final long serialVersionUID = 1L;
	JTextArea displayArea;
    static final String newline = System.getProperty("line.separator");
	protected static Vector<Vector<Client>> teams = null;
	static ServerMonitor frame;

    public ServerMonitor(String name) {
        super(name);
    }
    
    public void init(Vector<Vector<Client>> teams){
        this.teams = teams;
        /* Use an appropriate Look and Feel */
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        /* Turn off metal's use of bold fonts */
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        
        createAndShowGUI();
    }
    
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        frame = new ServerMonitor("Kayao server status");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        //Set up the content pane.
        frame.addComponentsToPane();
                
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    
    private void addComponentsToPane() {
        
        JButton button = new JButton("Clear");
        button.addActionListener(this);
                
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        displayArea.addKeyListener(this);
        displayArea.setMargin(new Insets(5,5,5,5));
        printClients();
        JScrollPane scrollPane = new JScrollPane(displayArea);
        scrollPane.setPreferredSize(new Dimension(500, 700));
        
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.PAGE_END);
    }
        
    /** Handle the button click. */
    public void actionPerformed(ActionEvent e) { displayArea.setText(""); }    
    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {}
    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {}
    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
    	updateText(e);
    }
    
    private void updateText(KeyEvent e){
        char c = e.getKeyChar();
        switch (c) {
        	case 'q':	frame.setVisible(false); break;
        	case 'c':	displayArea.setText(""); break;
        	case ' ':	printClients();	break;
        	default:	break;
        }
    }
    
    private void printClients(){
    	long uptime = System.currentTimeMillis()-KayaoValues.SERVER_START.getTime();
		displayArea.setText("SERVER IP:  "+KayaoValues.SERVER_IP+"\tPORT:  "+KayaoValues.SERVER_PORT+"\n\n");		
		displayArea.append("The server was started at: "+KayaoValues.SERVER_START.toString()+"\n");
		displayArea.append("Server uptime: "+convertUptime(uptime)+"\t milliseconds: "+uptime+"\n\n");
		displayArea.append("Clients: "+getNumClients()+" Kingdoms: "+KayaoValues.NUMBER_OF_KINGDOMS+" Teams: "+teams.size()+"\n\n");		
		displayArea.append("List of regions and kings: \n");
		displayArea.append("=====================================================================\n");
		displayArea.append(AreaManager.getRegions());
		displayArea.append("=====================================================================\n\n");
		displayArea.append("List of clients: \n");
		displayArea.append("=====================================================================\n");
		displayArea.append("NAME\tID\tIP\t\tTIME ONLINE\tTEAM\n");
		displayArea.append("=====================================================================");
		for (int j=0; j<teams.size(); j++){
			for (int i=0; i<teams.elementAt(j).size(); i++){
				displayArea.append("\n"+teams.elementAt(j).elementAt(i).toString());
			}
			if (j<(teams.size()-1)){
				displayArea.append("\n=====================================================================\n");
				displayArea.append("NAME\tID\tIP\t\tTIME ONLINE\tTEAM\n");
				displayArea.append("=====================================================================");				
			} else {
				displayArea.append("\n=====================================================================");				
			}
		}
		displayArea.append("\n\nKeyboard shortcuts:\n");		
		displayArea.append("space \t refresh screen\n");
		displayArea.append("c \t clear screen\n");
		displayArea.append("q \t close monitor (keeps server running)\n");
    }
    
    public String convertUptime(long uptime) {
		String format = String.format("%%0%dd", 2);
		uptime = uptime / 1000;
		String seconds = String.format(format, uptime % 60);
		String minutes = String.format(format, (uptime % 3600) / 60);
		String hours = String.format(format, uptime / 3600);
		String time =  hours + ":" + minutes + ":" + seconds;
    	return time;  
    }
    
    public int getNumClients(){
    	int numClients = 0;
    	for (int j=0; j<teams.size(); j++){
    		numClients += teams.elementAt(j).size();
    	}
    	return numClients;
    }
}
